package cn.com.do1.component.pay.pay.ui;

import cn.com.do1.common.dac.Pager;
import cn.com.do1.common.annotation.struts.*;
import cn.com.do1.common.exception.IllegalParameterException;
import cn.com.do1.common.framebase.struts.BaseAction;
import cn.com.do1.component.merchandise.merchandise.service.IMerchandiseService;
import cn.com.do1.component.merchandise.merchandise.vo.TbCzMerchandiseVO;
import cn.com.do1.component.merchant.merchant.dao.IMerchantDAO;
import cn.com.do1.component.merchant.merchant.service.IMerchantService;
import cn.com.do1.component.pay.pay.model.*;
import cn.com.do1.component.pay.pay.service.IPayService;
import cn.com.do1.component.pay.pay.vo.TbCzPayVO;
import cn.com.do1.component.pay.payinfo.model.TbCzPayInfoPO;
import cn.com.do1.component.systemmgr.role.model.TbDqdpRolePO;
import cn.com.do1.component.systemmgr.role.service.IRoleService;
import cn.com.do1.component.systemmgr.user.model.User;
import cn.com.do1.component.util.ExcelUtil;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import cn.com.do1.common.exception.BaseException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;

import cn.com.do1.common.util.AssertUtil;
import cn.com.do1.common.util.DateUtil;
import cn.com.do1.dqdp.core.ConfigMgr;
import cn.com.do1.dqdp.core.DqdpAppContext;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.icu.text.SimpleDateFormat;

/**
 * Copyright &copy; 2010 广州市道一信息技术有限公司 All rights reserved. User: ${user}
 */
public class PayAction extends BaseAction {
    private final static transient Logger logger = LoggerFactory.getLogger(PayAction.class);
    private IPayService payService;
    private TbCzPayPO tbCzPayPO;
    private String ids[];
    private String id;
    private String status;

    @Resource
    private IMerchandiseService merchandiseService;

    @Resource
    private IMerchantService chantService;

    @Resource
    private IRoleService roleService;

    public IPayService getPayService() {
        return payService;
    }

    @Resource
    public void setPayService(IPayService payService) {
        this.payService = payService;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "startDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "endDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "payId", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "payMoblie", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "userName", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "name", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("payList")
    public void ajaxSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        if (!isAdmin()) {
            User user = (User) DqdpAppContext.getCurrentUser();
            getSearchValue().put("userId", user.getId());
        }
        pager = payService.searchPay(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "startDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "endDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "payId", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "payMoblie", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "userName", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "name", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("myPayList")
    public void ajaxMySearch() throws Exception, BaseException {

        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        if (!isAdmin()) {
            User user = (User) DqdpAppContext.getCurrentUser();
            getSearchValue().put("userId", user.getId());
        }

        pager = payService.searchPay(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "新增成功", faileMsg = "新增失败"))
    public void ajaxAdd() throws Exception, BaseException {
        // todo:完成新增的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1003", successMsg = "更新成功", faileMsg = "更新失败"))
    public void ajaxUpdate() throws Exception, BaseException {
        // todo:完成更新的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "删除成功", faileMsg = "删除失败"))
    public void ajaxBatchDelete() throws Exception, BaseException {
        // 完成批量更新的代码
    }

    public void setTbCzPayPO(TbCzPayPO tbCzPayPO) {
        this.tbCzPayPO = tbCzPayPO;
    }

    public TbCzPayPO setTbCzPayPO() {
        return this.tbCzPayPO;
    }

    public void addTbCzPayPO() {
        super.ajaxAdd(tbCzPayPO);
    }

    public void updateTbCzPayPO() {
        super.ajaxUpdate(tbCzPayPO);
    }

    public void deleteTbCzPayPO() {
        if (AssertUtil.isEmpty(id))
            id = ids[0];
        tbCzPayPO._setPKValue(id);
        super.ajaxDelete(tbCzPayPO);
    }

    public void batchDeleteTbCzPayPO() {
        super.ajaxBatchDelete(TbCzPayPO.class, ids);
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxView() throws Exception, BaseException {
        TbCzPayVO tbCzPayVO = payService.getTbCzPayByPayID(id);
        addJsonObj("tbCzPayPO", tbCzPayVO);// 注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatus")
    public void updateStatus() {
        try {
            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayStatus(status);
            payService.updatePO(payPO, false);
        } catch (Exception e) {
            logger.error("更新支付订出错", e);

        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatusCompile")
    public void payUpdateStatusCompile() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            // payService.payUpdateStatusCompile(id, user.getUsername());

            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayEndDate(new Date());
            payPO.setPayUpdate(new Date());
            payPO.setPayStatus("2");
            payPO.setPayOper(user.getUsername());
            payService.updatePO(payPO, false);

            TbCzPayInfoPO info = new TbCzPayInfoPO();
            info.setPayId(id);
            info.setStatus(2);
            info.setUpdateDate(new Date());
            info.setOper(user.getUsername());
            info.setInfo("充值完成");
            payService.insertPO(info, true);

        } catch (Exception e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");

        } catch (BaseException e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatusFail")
    public void payUpdateStatusFail() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            // payService.payUpdateStatusCompile(id, user.getUsername());

            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayUpdate(new Date());
            payPO.setPayStatus("3");
            payPO.setPayOper(user.getUsername());
            payService.updatePO(payPO, false);

            TbCzPayInfoPO info = new TbCzPayInfoPO();
            info.setPayId(id);
            info.setStatus(3);
            info.setUpdateDate(new Date());
            info.setOper(user.getUsername());
            info.setInfo("充值失败");
            payService.insertPO(info, true);

        } catch (Exception e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");

        } catch (BaseException e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatusMoney")
    public void payUpdateStatusMoney() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            // payService.payUpdateStatusCompile(id, user.getUsername());

            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayUpdate(new Date());
            payPO.setPayStatus("4");
            payPO.setPayOper(user.getUsername());
            payService.updatePO(payPO, false);

            this.chantService.addMoney(payPO.getPayMerchatId(), payPO.getPayDiscountMoney());

            TbCzPayInfoPO info = new TbCzPayInfoPO();
            info.setPayId(id);
            info.setStatus(4);
            info.setUpdateDate(new Date());
            info.setOper(user.getUsername());
            info.setInfo("退款");
            payService.insertPO(info, true);

        } catch (Exception e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");

        } catch (BaseException e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatusAppeal")
    public void payUpdateStatusAppeal() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            // payService.payUpdateStatusCompile(id, user.getUsername());

            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayUpdate(new Date());
            payPO.setPayStatus("5");
            payPO.setPayOper(user.getUsername());
            payService.updatePO(payPO, false);

            TbCzPayInfoPO info = new TbCzPayInfoPO();
            info.setPayId(id);
            info.setStatus(5);
            info.setUpdateDate(new Date());
            info.setOper(user.getUsername());
            info.setInfo("申诉");
            payService.insertPO(info, true);

        } catch (Exception e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");

        } catch (BaseException e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatusAppealSuccess")
    public void payUpdateStatusAppealSuccess() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            // payService.payUpdateStatusCompile(id, user.getUsername());

            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayUpdate(new Date());
            payPO.setPayStatus("6");
            payPO.setPayOper(user.getUsername());
            payService.updatePO(payPO, false);

            TbCzPayInfoPO info = new TbCzPayInfoPO();
            info.setPayId(id);
            info.setStatus(6);
            info.setUpdateDate(new Date());
            info.setOper(user.getUsername());
            info.setInfo("申诉成功");
            payService.insertPO(info, true);

        } catch (Exception e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");

        } catch (BaseException e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "操作成功", faileMsg = "操作失败"))
    @ActionRoles("payUpdateStatusAppealFail")
    public void payUpdateStatusAppealFail() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            // payService.payUpdateStatusCompile(id, user.getUsername());

            TbCzPayPO payPO = payService.searchByPk(TbCzPayPO.class, id);
            payPO.setPayUpdate(new Date());
            payPO.setPayStatus("7");
            payPO.setPayOper(user.getUsername());
            payService.updatePO(payPO, false);

            TbCzPayInfoPO info = new TbCzPayInfoPO();
            info.setPayId(id);
            info.setStatus(7);
            info.setUpdateDate(new Date());
            info.setOper(user.getUsername());
            info.setInfo("申诉失败");
            payService.insertPO(info, true);

        } catch (Exception e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");

        } catch (BaseException e) {
            logger.error("更新支付订出错", e);
            setActionResult("1913", "更新支付订出错");
        }
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "初始化失败", successMsg = "初始化成功"))
    public void initItemMerchandise() {

        try {
            List<TbCzMerchandiseVO> list = merchandiseService.getMerchandise();
            addJsonArray("merchandiseList", list);

        } catch (Exception e) {
            setActionResult("1913", "初始化套餐列表数据错误");
            logger.error("初始化充值数据错误", e);
        } catch (BaseException e) {
            setActionResult("1913", "初始化套餐列表数据错误");
            logger.error("初始化充值数据错误", e);
        }
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "startDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "endDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "payId", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "payMoblie", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "userName", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "name", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("payExport")
    public String export() {
        Pager pager = new Pager(ServletActionContext.getRequest(), 9999999);

        List<TbCzPayVO> list = null;
        try {
            pager = payService.searchPay(getSearchValue(), pager);
            list = (List<TbCzPayVO>) pager.getPageData();

        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
        } finally {
        }

        if (!AssertUtil.isEmpty(list)) {

            // 调用导出方法，获取导出的文件
            String[] head =
                    {"订单号", "代理商账号", "代理商名称", "充值手机", "套餐名称", "充值状态", "套餐原价", "折扣价格", "充值请求时间", "充值完成时间", "更新时间", "操作人"};
            File excelFile = ExcelUtil.exportForExcel(head, list, TbCzPayVO.class);
            // 以流的形式输出导出的文件
            try {
                if (excelFile.exists()) {
                    String fileName = "流量充值列表" + DateUtil.formartCurrentDate() + ".xls";
                    InputStream is = new FileInputStream(excelFile);
                    HttpServletResponse response = ServletActionContext.getResponse();
                    OutputStream os = response.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                    response.reset();
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/ vnd.ms-excel");// 不同类型的文件对应不同的MIME类型

                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                    }
                    bos.flush();
                    bis.close();
                    bos.close();
                    is.close();
                    os.close();
                }
            } catch (Exception e) {
                logger.error("导入excel出错", e);
            }
        }

        return null;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "startDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "endDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "payId", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "payMoblie", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "userName", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "name", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    @ActionRoles("myPayExport")
    public String myExport() {
        Pager pager = new Pager(ServletActionContext.getRequest(), 9999999);
        User user = (User) DqdpAppContext.getCurrentUser();
        getSearchValue().put("userId", user.getId());

        List<TbCzPayVO> list = null;
        try {
            pager = payService.searchPay(getSearchValue(), pager);
            list = (List<TbCzPayVO>) pager.getPageData();

        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
        } finally {
        }

        if (!AssertUtil.isEmpty(list)) {

            // 调用导出方法，获取导出的文件
            String[] head =
                    {"订单号", "代理商账号", "代理商名称", "充值手机", "套餐名称", "充值状态", "套餐原价", "折扣价格", "充值请求时间", "充值完成时间", "更新时间", "操作人"};
            File excelFile = ExcelUtil.exportForExcel(head, list, TbCzPayVO.class);
            // 以流的形式输出导出的文件
            try {
                if (excelFile.exists()) {
                    String fileName = "流量充值列表" + DateUtil.formartCurrentDate() + ".xls";
                    InputStream is = new FileInputStream(excelFile);
                    HttpServletResponse response = ServletActionContext.getResponse();
                    OutputStream os = response.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                    response.reset();
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/ vnd.ms-excel");// 不同类型的文件对应不同的MIME类型

                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                    }
                    bos.flush();
                    bis.close();
                    bos.close();
                    is.close();
                    os.close();
                }
            } catch (Exception e) {
                logger.error("导入excel出错", e);
            }
        }

        return null;
    }

    public TbCzPayPO getTbCzPayPO() {
        return this.tbCzPayPO;
    }

    private boolean isAdmin() {
        boolean result = false;
        User user = (User) DqdpAppContext.getCurrentUser();
        if ("admin".equals(user.getUsername())) {
            return true;
        }

        try {
            List<TbDqdpRolePO> list = roleService.listRoleByUserId(user.getId());

            if (!AssertUtil.isEmpty(list)) {
                for (TbDqdpRolePO tbDqdpRolePO : list) {
                    String roleId = tbDqdpRolePO.getRoleId();
                    if (ConfigMgr.get("systemmgr", "adminRole", "0c7f6536-156d-468b-b81a-cfb5fd9918bc").equals(roleId)) {
                        result = true;
                        break;
                    }
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (BaseException e) {
            e.printStackTrace();
        }

        return result;
    }
}
